import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { getUserInfoApi, getMenuListApi } from '../../services/axios'
import type { UserInfoRes, MenuList } from '../../types/types'

export const getUserInfoAction = createAsyncThunk('user/getUserInfo', async () => {
  try { 
    const [userInfoRes, menuListRes] = await Promise.all([getUserInfoApi(), getMenuListApi()])
    return {
      userInfo: userInfoRes.data.data,
      sideMenuList: menuListRes.data.data.list
    }
  }catch(e) {
    return Promise.reject(e)
  }

})
interface State {
  userInfo: UserInfoRes | null
  sideMenuList: MenuList[]
  userLoading: boolean
}


const initialState: State = {
  userInfo: null,
  sideMenuList: [],
  userLoading: false
}

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers:{},

  extraReducers: builder => {
    builder
    .addCase(getUserInfoAction.pending, state => {
      state.userLoading = true
    })
    .addCase(getUserInfoAction.fulfilled, (state, { payload }) => {
      // console.log(payload)
      state.userInfo = payload.userInfo
      state.sideMenuList = payload.sideMenuList
      state.userLoading = false
    })
    .addCase(getUserInfoAction.rejected, (state ) => {
      state.userLoading = false
    })
  }


  // getUserInfoApi()
})

export default userSlice.reducer